package com.bicon.botu.mall.base.service.impl;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.bicon.botu.commons.constants.MallConstants;
import com.bicon.botu.core.base.common.Constants;
import com.bicon.botu.core.base.common.entity.BaseResult;
import com.bicon.botu.core.base.common.utils.JsonUtil;
import com.bicon.botu.core.base.common.utils.StringUtils;
import com.bicon.botu.mall.base.common.MallHomePageConstants;
import com.bicon.botu.mall.base.dto.ChannelDto;
import com.bicon.botu.mall.base.dto.ChannelGoodsDto;
import com.bicon.botu.mall.base.entity.Channel;
import com.bicon.botu.mall.base.entity.ChannelGoods;
import com.bicon.botu.mall.base.mapper.ChannelGoodsMapper;
import com.bicon.botu.mall.base.service.IChannelGoodsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 栏目商品 服务实现类
 *
 * @author 张凡
 * @date 2017/7/19 下午 14:49
 */
@Service
@Slf4j
@Transactional
public class ChannelGoodsServiceImpl extends ServiceImpl<ChannelGoodsMapper, ChannelGoods> implements IChannelGoodsService {
    @Autowired
    ChannelGoodsMapper channelGoodsMapper;

    /**
     * 添加频道商品
     *
     * @param goodsId     商品id
     * @param channelType 频道类型： 1-猜你喜欢 2-新品首发 3-人气推荐
     * @return
     */
    @Override
    public BaseResult add(String goodsId, Integer channelType) {
        boolean result;
        Integer rows = new ChannelGoods().selectCount(new EntityWrapper<ChannelGoods>()
                .eq("channel_type", channelType).eq("logic_delete", MallHomePageConstants.DEL_LOGIC_NORMAL));
        if (Objects.equals(channelType, MallHomePageConstants.GUESS_GOODS)) {
            if (rows >= MallHomePageConstants.GUESS_GOODS_NUM) {
                return new BaseResult(MallHomePageConstants.RESPONSE_CODE_604, MallHomePageConstants.RESPONSE_MESSAGE_604);
            }
        } else {
            if (rows >= MallHomePageConstants.CHANNEL_GOODS_NUM) {
                return new BaseResult(MallHomePageConstants.RESPONSE_CODE_604, MallHomePageConstants.RESPONSE_MESSAGE_604);
            }
        }
        Long mainPictureCount = this.channelGoodsMapper.countMainPictureByProductId(goodsId);
        if(mainPictureCount<=0){
            return new BaseResult(MallHomePageConstants.RESPONSE_CODE_500, "选择的商品没有主片，请重新选择");
        }

        ChannelGoods channelGoods = new ChannelGoods();
        channelGoods.setChannelType(channelType);
        channelGoods.setGoodsId(goodsId);
        channelGoods.setGoodsSort(++rows);
        channelGoods.preInsert();
        result = channelGoods.insert();
        if (!result) {
            return new BaseResult(MallHomePageConstants.RESPONSE_CODE_500, MallHomePageConstants.RESPONSE_MESSAGE_500);
        }
        //修改商品展示状态
        channelGoodsMapper.updateProductState(goodsId, "1");
        return new BaseResult(MallHomePageConstants.RESPONSE_CODE_200, MallHomePageConstants.RESPONSE_MESSAGE_200);
    }

    /**
     * 修改频道商品排序
     *
     * @param goodsIdJson 商品id集合
     * @param channelType 频道类型： 1-猜你喜欢 2-新品首发 3-人气推荐
     * @return
     */
    @Override
    public BaseResult updateSort(String goodsIdJson, Integer channelType) {
        ArrayList<String> goodsIdList = JsonUtil.fromJson(goodsIdJson, ArrayList.class);
        boolean result;
        //删除这些商品再新增
        result = new ChannelGoods().delete(new EntityWrapper<ChannelGoods>()
                .eq("channel_type", channelType).eq("logic_delete", MallHomePageConstants.DEL_LOGIC_NORMAL));
        if (!result) {
            log.info("删除商品失败");
            return new BaseResult(MallHomePageConstants.RESPONSE_CODE_500, MallHomePageConstants.RESPONSE_MESSAGE_500);
        }
        Integer rows = new ChannelGoods().selectCount(new EntityWrapper<ChannelGoods>()
                .eq("channel_type", channelType).eq("logic_delete", MallHomePageConstants.DEL_LOGIC_NORMAL));
        //新增商品
        for (int i = 0; i < goodsIdList.size(); i++) {
            if (MallHomePageConstants.GUESS_GOODS.equals(channelType)) {
                if (rows >= MallHomePageConstants.GUESS_GOODS_NUM) {
                    return new BaseResult(MallConstants.RESPONSE_CODE_604, MallConstants.RESPONSE_MESSAGE_604);
                }
            } else {
                if (rows >= MallHomePageConstants.CHANNEL_GOODS_NUM) {
                    return new BaseResult(MallConstants.RESPONSE_CODE_604, MallConstants.RESPONSE_MESSAGE_604);
                }
            }
            ChannelGoods channelGoods = new ChannelGoods();
            channelGoods.setChannelType(channelType);
            channelGoods.setGoodsId(goodsIdList.get(i));
            channelGoods.setGoodsSort(++rows);
            channelGoods.preInsert();
            result = channelGoods.insert();
            if (!result) {
                log.info("添加商品失败");
                return new BaseResult(MallHomePageConstants.RESPONSE_CODE_500, MallHomePageConstants.RESPONSE_MESSAGE_500);
            }
        }
        return new BaseResult(MallHomePageConstants.RESPONSE_CODE_200, MallHomePageConstants.RESPONSE_MESSAGE_200);
    }

    /**
     * 删除频道商品
     *
     * @param goodsId     商品id
     * @param channelType 频道类型： 1-猜你喜欢 2-新品首发 3-人气推荐
     * @return
     */
    @Override
    public BaseResult delete(String goodsId, Integer channelType) {
        //判断此商品是否存在
        ChannelGoods channelGoods = new ChannelGoods().selectOne(new EntityWrapper<ChannelGoods>().eq("goods_id", goodsId)
                .eq("channel_type", channelType).eq("logic_delete", MallHomePageConstants.DEL_LOGIC_NORMAL));
        if (channelGoods == null) {
            return new BaseResult(MallHomePageConstants.RESPONSE_CODE_404, MallHomePageConstants.RESPONSE_MESSAGE_404);
        }
        //物理删除
        boolean result = channelGoods.deleteById();
        if (!result) {
            return new BaseResult(MallHomePageConstants.RESPONSE_CODE_500, MallHomePageConstants.RESPONSE_MESSAGE_500);
        }
        //修改商品展示状态
        channelGoodsMapper.updateProductState(goodsId, "0");
        return new BaseResult(MallHomePageConstants.RESPONSE_CODE_200, MallHomePageConstants.RESPONSE_MESSAGE_200);
    }

    /**
     * 获取频道商品并一次返回(客户端)
     *
     * @return
     */
    @Override
    public List<ChannelDto> getAllChannelGoods() {
        List<ChannelDto> channelDtoList = new ArrayList<>();
        List<Integer> channelTypes = new ArrayList<>();
        List<Channel> channels = new Channel().selectList(new EntityWrapper<Channel>().eq("logic_delete", Constants.DEL_LOGIC_NORMAL));
        if (channels.size() > 0 && channels != null) {
            for (Channel channel : channels) {
                if (!(channel.getChannelType().equals(MallHomePageConstants.CAREFULLY_CHOSEN_TYPE) || channel.getChannelType().equals(MallHomePageConstants.GUESS_GOODS))) {
                    channelTypes.add(channel.getChannelType());
                }
            }
        }
        if (channelTypes.size() > 0 && channelTypes != null) {
            for (Integer type : channelTypes) {
                channelDtoList.add(getAppChannelGoods(type));
            }
        }
        return channelDtoList;
    }

    /**
     * 获取频道和频道商品（客户端）
     *
     * @return
     */
    @Override
    public ChannelDto getAppChannelGoods(Integer channelType) {
        Map<String, Object> map = new HashMap<>();
        map.put("channelType", channelType);
        map.put("logicDelete", Constants.DEL_LOGIC_NORMAL);
        map.put("channelFlag", MallHomePageConstants.ON);
        map.put("isMain", MallHomePageConstants.PICTURE_IS_MAIN);
        map.put("upShelves", MallHomePageConstants.PRODUCT_UP_SHELVES);
        List<ChannelGoodsDto> channelGoodsDtoList = channelGoodsMapper.selectChannelGoods(map);
        Channel channel = new Channel().selectOne(new EntityWrapper<Channel>().eq("channel_type", channelType)
                .eq("logic_delete", MallHomePageConstants.DEL_LOGIC_NORMAL));
        ChannelDto channelDto = new ChannelDto();
        channelDto.setChannelType(channel.getChannelType());
        channelDto.setChannelTitle(channel.getChannelTitle());
        List<ChannelGoodsDto> channelGoodsDtos = new ArrayList<>();
        if (channelType.equals(MallHomePageConstants.HOT_GOODS)) {
            if (channelGoodsDtoList.size() == 0) {
                List<ChannelGoodsDto> list = this.getMostBrowseGoods(MallHomePageConstants.CHANNEL_GOODS_NUM - channelGoodsDtoList.size());
                channelGoodsDtos.addAll(channelGoodsDtoList);
                channelGoodsDtos.addAll(list);
                channelDto.setChannelGoodsDtoList(channelGoodsDtos);
            } else {
                channelDto.setChannelGoodsDtoList(channelGoodsDtoList);
            }
        } else {
            channelDto.setChannelGoodsDtoList(channelGoodsDtoList);
        }
        return channelDto;
    }

    /**
     * 查询频道和频道商品（后台）
     *
     * @param channelType 频道类型：1-猜你喜欢 2-新品首发 3-人气推荐
     * @return
     */
    @Override
    public ChannelDto getChannelGoods(Integer channelType) {
        Map<String, Object> map = new HashMap<>();
        map.put("channelType", channelType);
        map.put("logicDelete", Constants.DEL_LOGIC_NORMAL);
        map.put("isMain", MallHomePageConstants.PICTURE_IS_MAIN);
        map.put("upShelves", MallHomePageConstants.PRODUCT_UP_SHELVES);
        List<ChannelGoodsDto> channelGoodsDtoList = channelGoodsMapper.selectChannelGoods(map);
        Channel channel = new Channel().selectOne(new EntityWrapper<Channel>().eq("channel_type", channelType)
                .eq("logic_delete", MallHomePageConstants.DEL_LOGIC_NORMAL));
        ChannelDto channelDto = new ChannelDto();
        channelDto.setChannelType(channel.getChannelType());
        channelDto.setChannelTitle(channel.getChannelTitle());
        channelDto.setChannelGoodsDtoList(channelGoodsDtoList);
        return channelDto;
    }

    /**
     * 修改频道商品
     *
     * @param id          主键id
     * @param goodsId     商品id
     * @param channelType 频道类型： 1-猜你喜欢 2-新品首发 3-人气推荐
     * @return
     */
    @Override
    public BaseResult update(Integer id, String goodsId, Integer channelType) {
        //判断此商品是否存在
        ChannelGoods channelGoods = new ChannelGoods().selectOne(new EntityWrapper<ChannelGoods>()
                .eq("id", id).eq("logic_delete", MallHomePageConstants.DEL_LOGIC_NORMAL));
        if (channelGoods == null) {
            return new BaseResult(MallHomePageConstants.RESPONSE_CODE_404, MallHomePageConstants.RESPONSE_MESSAGE_404);
        }
        channelGoods.setGoodsId(goodsId);
        channelGoods.preUpdate();
        boolean result = channelGoods.updateById();
        if (!result) {
            return new BaseResult(MallHomePageConstants.RESPONSE_CODE_500, MallHomePageConstants.RESPONSE_MESSAGE_500);
        }
        return new BaseResult(MallHomePageConstants.RESPONSE_CODE_200, MallHomePageConstants.RESPONSE_MESSAGE_200);
    }

    /**
     * 查询浏览最多的商品(人气推荐)
     *
     * @return
     */
    @Override
    public List<ChannelGoodsDto> getMostBrowseGoods(Integer num) {
        Map<String, Object> map = new HashMap<>();
        map.put("num", num);
        map.put("logicDelete", Constants.DEL_LOGIC_NORMAL);
        map.put("type", MallHomePageConstants.BROWSE_TYPE);
        map.put("isMain", MallHomePageConstants.PICTURE_IS_MAIN);
        map.put("upShelves", MallHomePageConstants.PRODUCT_UP_SHELVES);
        return channelGoodsMapper.mostBrowseGoods(map);
    }


    /**
     * 获取猜你喜欢的商品（猜你喜欢）
     *
     * @param pageNo   页码
     * @param pageSize 每页显示条数
     * @param userId   用户id
     * @return
     */
    @Override
    public Page<ChannelGoodsDto> getGuessChannelGoods(Integer pageNo, Integer pageSize, String userId) {
        Page<ChannelGoodsDto> page = new Page<ChannelGoodsDto>(pageNo, pageSize);
        //获取系统设置的商品
        Map<String, Object> map1 = new HashMap<>();
        map1.put("channelType", MallHomePageConstants.GUESS_GOODS);
        map1.put("logicDelete", Constants.DEL_LOGIC_NORMAL);
        map1.put("channelFlag", MallHomePageConstants.ON);
        map1.put("isMain", MallHomePageConstants.PICTURE_IS_MAIN);
        map1.put("upShelves", MallHomePageConstants.PRODUCT_UP_SHELVES);
        List<ChannelGoodsDto> channelGoodsDtoList = channelGoodsMapper.selectChannelGoods(map1);
        //查询对应的猜你喜欢商品
        Map<String, Object> map = new HashMap<>();
        map.put("num", MallHomePageConstants.GUESS_GOODS_NUM - channelGoodsDtoList.size());
        map.put("logicDelete", Constants.DEL_LOGIC_NORMAL);
        map.put("isMain", MallHomePageConstants.PICTURE_IS_MAIN);
        map.put("userId", userId);
        map.put("type", MallHomePageConstants.BROWSE_TYPE);
        map.put("upShelves", MallHomePageConstants.PRODUCT_UP_SHELVES);
        List<ChannelGoodsDto> channelGoodsDtos = channelGoodsMapper.getGuessChannelGoodsFromBrowse(map);
        channelGoodsDtoList.addAll(channelGoodsDtos);
        //去重
        List<ChannelGoodsDto> channelGoodsDtos1 = new ArrayList<>();
        HashMap<String, String> hashMap = new HashMap<>();
        for (ChannelGoodsDto channelGoodsDto : channelGoodsDtoList) {
            if (channelGoodsDto == null) {
                continue;
            }
            String goodsId = channelGoodsDto.getGoodsId();
            if (goodsId != null) {
                String value = hashMap.get(goodsId);
                if (StringUtils.isBlank(value)) { //如果value是空的  说明取到的这个goodsId是第一次取到
                    hashMap.put(goodsId, goodsId);
                    channelGoodsDtos1.add(channelGoodsDto); //channelGoodsDtos1就是我们想要的去重之后的结果
                } else {
                    continue;
                }
            }
        }
        if (pageNo <= 0) {
            pageNo = 1;
        }
        //记录一下数据一共有多少条
        int total = channelGoodsDtos1.size();
        //实例化一个接受分页处理之后的数据
        List<ChannelGoodsDto> afterList = new ArrayList<ChannelGoodsDto>();
        for (int i = (pageNo - 1) * pageSize; i < (((pageNo - 1) * pageSize) + pageSize > total ? total : ((pageNo - 1) * pageSize) + pageSize); i++) {
            //然后将数据存入afterList中
            afterList.add(channelGoodsDtoList.get(i));
        }
        //然后将处理后的数据集合进行返回
        page.setRecords(afterList);
        page.setTotal(total);
        return page;
    }

    /**
     * 获取App大首页精选商品频道的3个商品
     */
    @Override
    public List<ChannelGoodsDto> getAppHomePageChannelGoods() {
        Map<String, Object> map = new HashMap<>();
        map.put("channelType", MallHomePageConstants.NEW_GOODS);
        map.put("logicDelete", Constants.DEL_LOGIC_NORMAL);
        map.put("channelFlag", MallHomePageConstants.ON);
        map.put("isMain", MallHomePageConstants.PICTURE_IS_MAIN);
        map.put("upShelves", MallHomePageConstants.PRODUCT_UP_SHELVES);
        map.put("num", MallHomePageConstants.NUM_LIMIT);
        List<ChannelGoodsDto> channelGoodsDtoList = channelGoodsMapper.selectChannelGoods(map);
        return channelGoodsDtoList;
    }

    @Override
    public void updateProductState(String productId, String state) {
        channelGoodsMapper.updateProductState(productId, state);
    }


}
